package com.hudson.broker.handler.netty;

import com.hudson.broker.BrokerController;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/7/13 19:53
 **/
public class BrokerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(BrokerHandler.class);
    private static final ConcurrentHashMap<String, Channel> CHANNEL_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>();

    public static List<Channel> getChannelList(){
        return new ArrayList<>(CHANNEL_CONCURRENT_HASH_MAP.values());
    }
    public static ConcurrentHashMap<String, Channel> getChannelMap(){
        return CHANNEL_CONCURRENT_HASH_MAP;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 检查 broker 是否已完全启动
        if (BrokerController.startCountDownLatch.getCount() > 0) {
            logger.warn("Broker 尚未完全启动，拒绝连接");
            ctx.close();
            return;
        }else {
            logger.debug("{} 连接成功",ctx.name());
            Channel channel = ctx.channel();
            CHANNEL_CONCURRENT_HASH_MAP.put(channel.id().asLongText(),channel);
        }
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("{} 断开连接",ctx.name());
        Channel channel = ctx.channel();
        CHANNEL_CONCURRENT_HASH_MAP.remove(channel.id().asLongText());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("Serve 收到消息:" + msg);
        ctx.fireChannelRead(msg);
    }
}
